package leetcode.swordoffer;

import java.util.Stack;

public class SO24 {
    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        n1.next = n2;
        n2.next = n3;
        SO24 am = new SO24();
        am.reverseList3(n1);
    }

    /**
     * 借助栈
     * 1. 先把节点放入栈内
     */
    public ListNode reverseList3(ListNode head) {
        if(head == null)
            return null;
        Stack<ListNode> st = new Stack<>();
        while (head != null) {
            st.add(head);
            head = head.next;
        }
        ListNode newHead = st.pop();
        ListNode temp = newHead;
        while (!st.empty()){
            temp.next = st.pop();
            temp = temp.next;
        }
        temp.next = null;
        return newHead;
    }
    // 递归
    public ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHd = reverseList2(head.next);
        head.next.next = head;
        head.next = null;
        return newHd;
    }

    /**
     * m1: 使用栈
     * m2: 双指针迭代
     * m3： 使用递归
     */
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode temp = null;
        while (cur != null) {
            temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
}
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

